package com.conversationboard.model.subscriptions;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

public class Subscriptions {

	public static List<Integer> getSupersetOfSubscribedBoards() throws SQLException {

		Connection connection = null;
		List<Integer> boardIDs = new LinkedList<Integer>();

		try {

			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.GET_SUPERSET_OF_SUBSCRIBED_BOARDS);
			statement.execute();

			ResultSet resultSet = statement.getResultSet();

			while (resultSet.next()) {
				boardIDs.add(resultSet.getInt("boardid"));
			}

			return boardIDs;

		} finally {
			Database.close(connection);
		}
	}


	public static Map<String, Subscription> getAll() throws SQLException {

		Map<String, Subscription> subscriptions = new HashMap<String, Subscription>();

		Connection connection = null;

		try {

			/* (1) Get the subscriptions */

			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.GET_SUBSCRIPTIONS);
			statement.execute();

			ResultSet resultSet = statement.getResultSet();

			while (resultSet.next()) {

				String emailAddress = resultSet.getString("loginid");
				int boardId = resultSet.getInt("boardid");

				if (subscriptions.containsKey(emailAddress)) {
					subscriptions.get(emailAddress).getBoards().add(boardId);
				} else {
					Subscription subscription = new Subscription();
					subscription.setEmailAddress(emailAddress);
					subscription.getBoards().add(boardId);
					subscriptions.put(emailAddress, subscription);
				}
			}

			statement.close();

			return subscriptions;

		} finally {
			Database.close(connection);
		}
	}

}
